<template>
  <!--标签管理-->
  <el-row style="height:100%">
    <page>
      <pageheader :event="'tagPopUp'" :isShow="buttonPermissions.isAdd">
        标签管理
      </pageheader>
      <div class="page-content">
        <el-card class="box-card tag-card">
          <el-row>
            <span class="tag-name">搜索标签类型：</span>
            <el-select v-model="type"
                       @change="changeType"
                       size="small"
                       filterable
                       clearable
                       placeholder="请输入或选择标签类型"
                       style="width:300px">
              <el-option
                v-for="item in typeList"
                :key="item.type"
                :label="item.name"
                :value="item.type">
              </el-option>
            </el-select>
            <span class="tag-name">搜索标签名称：</span>
            <el-input placeholder="请输入标签名称" v-model="typeName" size="small" style="width: 300px">
              <el-button @click="searchTypeName" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-row>
          <TreeTable
            :tableData="showOptions"
            :columns="columns"
            @tagDel="tagDel"
            border>
          </TreeTable>
        </el-card>
        <el-dialog v-dialogDrag :title="pageTitle" :visible.sync="isShow" @close="closeDialog('ruleForm')"
                   :modal-append-to-body="false" :close-on-click-modal="false" width="800px">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px">
            <el-form-item label="标签ID" prop="name">
              <el-input v-model="ruleForm.id" size="small" style="width:450px"></el-input>
            </el-form-item>
            <el-form-item label="标签名称" prop="name">
              <el-input v-model="ruleForm.name" size="small" style="width:450px"></el-input>
            </el-form-item>
            <el-form-item label="标签类型" prop="type">
              <el-radio-group v-model="ruleForm.type" size="small">
                <el-radio v-for="item in typeList" :label="item.type" :key="item.type">{{item.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <el-button type="primary" @click="confirmDialog('ruleForm')" size="small">保 存</el-button>
          </div>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .page-content {
    .tag-card{
      >.el-card__body{
        >.el-row{
          margin-bottom: 12px;
        }
      }
    }
    padding: 15px;
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
    .search-input{
      width: 300px;
      display: inline-block;
    }
    .tag-name{
      font-size: 14px;
      margin-left: 20px;
    }
  }
</style>
<script>
import page from "@/components/page/page";
import pageheader from "@/components/page/pageheader";
import TreeTable from "@/components/common/treeTable";
export default {
  data() {
    return {
      pageTitle: "标签管理",
      options: [],//原始表格数据
      showOptions: [],//显示表格数据
      typeList: [],//搜索框标签类型数据
      isShow: false,
      type:'',//搜索标签类型
      typeName:'',//搜索标签名称
      columns: [
        {
          text: "ID",
          value: "id",
          align: "center",
          width: 100
        },
        {
          text: "标签名称",
          value: "name",
          align: "center",
          // width: 200
        },
        {
          text: "标签类型",
          value: "typeName",
          align: "center",
          // width: 300
        },
      ],
      ruleForm:{
        id:'',
        name:'',
        type:'',
      },
      rules: {
        id: [{ required: true, message: "请输入标签ID", trigger: "blur"}],
        name: [{ required: true, message: "请输入标签名称", trigger: "blur"}],
        type: [{ required: true, message: "请选择标签类型", trigger: "change"}],
      },
      buttonPermissions:{
        isAdd:false,
        isDel:false,
      }
    }
  },
  inject: ["reload"],
  components: {
    page,
    pageheader,
    TreeTable
  },
  created() {
    this.getTypeList()
    //判断是否有按钮权限
    if(sessionStorage.buttonPermissions){
      this.configPermissions(JSON.parse(sessionStorage.buttonPermissions))
    }
  },
  mounted() {
    this.$Bus.$on("tagPopUp", data => {
      this.isShow = data;
    });
  },
  beforeDestroy(){
    //销毁Bus绑定事件
    this.$Bus.$off('tagPopUp')
  },
  methods: {
    //配置按钮权限，根据权限不同调整表头渲染参数
    configPermissions(val){
      let buttonPermissions = val
      let menuButtonPermissions = [];//按钮权限数组
      let operation = {
        text: "操作",
        value: "",
        align: "center",
        width: 150,
        button:[]
      };//操作
      buttonPermissions.forEach(e =>{
        for(let key in e){
          if(key == 'menu_code'){
            menuButtonPermissions.push(e[key])
          }
        }
      });
      this.buttonPermissions.isAdd = menuButtonPermissions.includes('tagAdd') ? true : false; //是否有新增权限
      this.buttonPermissions.isDel = menuButtonPermissions.includes('tagDelete') ? true : false; //是否有删除权限

      //删除权限配置
      if(this.buttonPermissions.isDel){
        operation.button.push( {
          name:'删除',
          type:'danger',
          event:'tagDel',
        },)
        this.columns.push(operation)
      }
    },

    //获取标签表格
    getTag(type = '') {
      let url = '/sys/tags/list?type='+ type;
      this.$api.get(url)
      .then(data =>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          //遍历数据将
          data.data.forEach(x =>{
            return x.type_name = x.name.split('-')[0]
          })
          for(let i in data.data){
            for(let j in this.typeList){
              if(data.data[i].type == this.typeList[j].type){
                data.data[i].typeName = this.typeList[j].name
              }
            }

          }
          this.options = data.data;//存储原始表格数据
          this.typeName = '';//清空收缩标签名称
          this.showOptions = [...data.data];//赋值显示表格数据
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //获取全部标签类型
    getTypeList(){
      let url = '/sys/tags/type_list'
      this.$api.get(url)
      .then(data =>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.typeList = data.data
        }
        this.getTag();
      })
      .catch(err=>{
         console.log(err);
        this.typeList = []
        this.$Bus.$emit('Loading',false)
      })
    },
    //删除按钮点击事件
    tagDel(data){
      this.$confirm("是否删除‘"+ data.name +"’？", "提示",{
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center:true
      })
      .then(() => {
        this.$Bus.$emit('Loading',true)
        this.delData(data.id);
      })
      .catch(() => {});
    },
    //删除接口
    delData(id) {
      let url = "sys/tags/del_tag";
      this.$api.delete(url, { id: id })
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.getTag(this.type)
          this.$message({
            message: "删除成功",
            type: "success"
          });
        }
      })
      .catch(err => {
         console.log(err);
        this.$Bus.$emit('Loading',false)
      });
    },
    //选择标签类型change事件
    changeType(val){
      this.$Bus.$emit('Loading',true)
      this.getTag(val)
    },
    //搜索标签名称click事件
    searchTypeName(){
      let val = this.typeName
      let options = this.options
      let newOptions = [];
      if(val){
        for(let i in options){
          if(options[i].name.includes(val)){
            newOptions.push(options[i])
          }
        }
        this.showOptions = [...newOptions]
      }else{
        this.showOptions = [...options]
      }
    },
    //关闭模态框
    closeDialog(formName){
      this.resetForm(formName)
      this.$Bus.$emit('Loading',false)
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //模态框保存按钮
    confirmDialog(formName) {
      let model = null
      let url = ''
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$Bus.$emit('Loading',true)
          model = this.$refs[formName].model;
          url = "/sys/tags/add_tag?name=" + model.name + '&type=' + model.type + '&id='+ model.id
          this.addTag(url);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //添加标签
    addTag(url){
      this.$api.post(url)
      .then(data =>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.getTag(this.type)
          this.$message({
            message: "新增成功",
            type: "success"
          });
          this.isShow = false
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    }
  },
  watch: {}
}
</script>
